<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 商城小程序公共API服务
 */
namespace app\ais\controller\api\v1;
use app\ais\controller\api\Base;
use app\ais\model\AisCity;
use app\ais\model\AisShop;
use app\ais\model\AisShopCate;
use app\ais\model\AisShopOrder;
use app\ais\model\AisStore;
use app\common\model\SystemUser;
use util\Util;

class Shop extends Base{

    protected $store_ids;

    /**
     * 初始化API并读取城市或你的经纬度
     * @return void
     */
    public function initialize() {
        parent::initialize();
        $citycode = $this->request->param('citycode/d',0);
        if($citycode){
            $this->store_ids = AisStore::whereIn('citycode', AisCity::whereIn('parent_id', AisCity::where(['code' => $citycode])->column('parent_id'))->column('code'))->column('id');
        }
    }
    /**
     * 读取单个商品信息
     * @param integer $id 商品ID
     * @return void
     */
    public function item(){
        $param['id'] = $this->request->param('id/d',0);
        $this->apiSign($param);
        $item = AisShop::with(['store'	=> function($query) {
            $query->field('id,img,create_time,tags,name,address,longitude,latitude');
        },'coupon' => function($query) {
            $query->field('id,types,discount,price,amount');
        }])->where(['is_sale'=>1,'id' => $param['id'],'member_miniapp_id' => $this->miniapp_id])
        ->field('id,store_id,category_id,warehouse_num,warehouse_sellnum,share_price,share_vip_price,vip_price,like,group_title,group_img,group_note,coupon_id,name,title,img,imgs,points_price,sell_price,market_price,end_time,content,notice,keyword')
        ->find();
        if(empty($item)){
            return enjson(204);
        }
        $item->like += 1;
        $item->save();
        //产品信息
        $item->content      = str_replace('<img', '<img class="img" style="max-width:100%;height:auto"',dehtml($item->content));
        $item->notice       = str_replace('<img', '<img class="img" style="max-width:100%;height:auto"',dehtml($item->notice));
        $item->market_price = money($item->market_price);
        $item->sell_price   = money($item->sell_price);
        $item->coupon_price = AisShop::couponPrice($item->sell_price,$item->coupon);
        $item->points_price = money($item->points_price);
        $item->share_price  = ($item->sell_price-$item->vip_price-$item->points_price-$item->coupon_price)*$item->share_price/100;
        $item->share_vip_price  = ($item->sell_price-$item->vip_price-$item->points_price-$item->coupon_price)*$item->share_vip_price/100;
        $item->warehouse_sellnum = $item->warehouse_sellnum + AisShopOrder::where(['shop_id' => $item->id,'paid_at'=>1])->count();
        $item->end_time          = ($item->warehouse_num ? (($item->end_time + 60 * 10) - time()) * 1000 : 0) ?: 0;
        //店铺信息
        $store = [];
        if($item->store_id > 0){
            $store['img']         = $item->store->img;
            $store['name']        = $item->store->name; 
            $store['address']     = $item->store->address; 
        }
        $item['store'] = $store;
        return enjson(200,$item);
    }

   /**
     * 首页显示
     */
    public function index(){
        $this->apiSign(['citycode' => $this->request->param('citycode')]);
        $where['member_miniapp_id'] = $this->miniapp_id;
        $where['types']             = 1;
        $where['is_sale']           = 1;
        $where['is_del']            = 0;
        if ($this->store_ids) {
            $where['store_id'] = $this->store_ids;
        }
        $rel = AisShop::where($where)->field('id,category_id,name,title,img,share_price,points_price,warehouse_num,sell_price,market_price,vip_price,coupon_id,end_time,update_time')->limit(8)->select();
        $data = [];
        foreach ($rel as $key => $value) {
            $data[$key] = $value;
            $data[$key]['coupon_price'] = AisShop::couponPrice($value->sell_price,$value->coupon);
            $data[$key]['img']          = $value->img;
            $data[$key]['tags']         = time()-$value->update_time <= 86400 ? '上新':'';
            $end_time                   = $value['warehouse_num'] ? (($value->end_time + 60 * 10) - time()) * 1000 : 0;
            $data[$key]['end_time']     = $end_time ?: 0;
        }
        return enjson(200,$data);
    }

   /**
     * 首页推荐专题
     */
    public function special(){
        $this->apiSign(['citycode' => $this->request->param('citycode')]);
        $cate = AisShopCate::where(['member_miniapp_id' => $this->miniapp_id,'types' => 1])->field('id,title,show_type,content,picture')->select();
        if(empty($cate)){
            return enjson(204);
        }
        $where['member_miniapp_id'] = $this->miniapp_id;
        $where['types']             = 2;
        $where['is_sale']           = 1;
        $where['is_del']            = 0;
        $where['category_id']       = array_column($cate->toArray(),'id');;
        if ($this->store_ids){
            $where['store_id'] = $this->store_ids;
        }
        $rel = AisShop::where($where)->field('id,category_id,name,title,img,share_price,points_price,warehouse_num,sell_price,market_price,vip_price,coupon_id,end_time,update_time')->limit(6)->select();
        $shop = [];
        foreach ($rel as $key => $value) {
            $shop[$key] = $value;
            $shop[$key]['coupon_price'] = AisShop::couponPrice($value->sell_price,$value->coupon);
            $shop[$key]['img']          = $value->img;
            $shop[$key]['tags']         = time()-$value->update_time <= 86400 ? '上新':'';
            $end_time                   = $value['warehouse_num'] ? (($value->end_time + 60 * 10) - time()) * 1000 : 0;
            $shop[$key]['end_time']     = $end_time ?: 0;
        }
        $goods = dataGroup($shop,'category_id');
        $data = [];
        foreach ($cate as $key => $value) {
            if(!empty($goods[$value->id])){
                $data[$key] = $value;
                $data[$key]['goods'] = $goods[$value->id];
            }
        }
        return enjson(200,$data);
    }
   
   /**
     * 专栏产品展示
     */
    public function lists(){
        $param['id']       = $this->request->param('id/d');
        $param['page']     = $this->request->param('page/d',0);
        $param['citycode'] = $this->request->param('citycode/d',0);
        $this->apiSign($param);
        if ($this->store_ids){
            $where['store_id'] = $this->store_ids;
        }
        $cate = [];
        if($param['page'] == 1){
            $cate = AisShopCate::where(['member_miniapp_id' => $this->miniapp_id,'id' => $param['id']])->field('id,title,content,picture')->find();
            if(empty($cate)){
                return enjson(403);
            }
        }
        $rel = AisShop::with(['store' => function($query) {
            $query->field('name,id,address,longitude,latitude');
        }])->where(['is_sale' => 1,'is_del' => 0,'category_id' => $param['id']])->field('id,share_price,store_id,category_id,name,title,img,warehouse_num,points_price,sell_price,market_price,vip_price,coupon_id,end_time,update_time')->page($param['page'],10)->select();
        if($rel->isEmpty()){
            return enjson(204);
        }
        $shop = [];
        foreach ($rel as $key => $value) {
            $shop[$key] = $value;
            $shop[$key]['coupon_price'] = AisShop::couponPrice($value->sell_price,$value->coupon);
            $shop[$key]['img']          = $value->img;
            $shop[$key]['tags']         = time()-$value->update_time <= 86400 ? '上新':'';
            $end_time                   = $value['warehouse_num'] ? (($value->end_time + 60 * 10) - time()) * 1000 : 0;
            $shop[$key]['end_time']     = $end_time ?: 0;
            $shop[$key]['store']        = $value->store;
        }
        return enjson(200,'成功',['shop' => $shop,'special' => $cate]);
    }

    /**
     * 查询指定商家的商品
     */
    public function store(){
        $param['page']    = $this->request->param('page/d',1);
        $param['store_id']= $this->request->param('store_id/d',0);
        $param['types']   = $this->request->param('types/d');
        $param['keyword'] = $this->request->param('keyword');
        $this->apiSign($param);
        $where = [];
        $where['is_del']  = 0;
        $where['is_sale'] = 1;
        $where['member_miniapp_id'] = $this->miniapp_id;
        if($param['types']){
            $where['types'] = $param['types'];
        }
        if($param['store_id']){
            $where['store_id'] = $param['store_id'];
        }
        $rel = AisShop::where($where)->withSearch(['name'],['name' => $param['keyword']])->field('id,share_price,store_id,category_id,name,title,img,warehouse_num,points_price,sell_price,market_price,vip_price,coupon_id,end_time,update_time')->page($param['page'],10)->select();
        if($rel->isEmpty()){
            return enjson(204);
        }
        $data = [];
        foreach ($rel as $key => $value) {
            $data[$key] = $value;
            $data[$key]['coupon_price'] = AisShop::couponPrice($value->sell_price,$value->coupon);
            $data[$key]['img']          = $value->img;
            $end_time                   = $value['warehouse_num'] ? (($value->end_time + 60 * 10) - time()) * 1000 : 0;
            $data[$key]['end_time']     = $end_time ?: 0;
        }
        return enjson(200,$data);
    }

    /**
     * 单个商品下单用户列表
     */
    public function orderUser(){
        $param['id'] = $this->request->param('id/d',0);
        $this->apiSign($param);
        $order = AisShopOrder::where(['shop_id' => $param['id']])->limit(6)->select();
        $data = [];
        if($order->isEmpty()){
            $user = SystemUser::where(['member_miniapp_id' => $this->miniapp_id])->field('face')->limit(6)->select()->toArray();
            $data = array_column($user,'face');
        }else{
            foreach ($order as $key => $value) {
                $data[$key] = $value->user->face;
            }
        }
        $new_order['id']          = 0;
        $new_order['create_time'] = 0;
        if($this->user){
            $info = AisShopOrder::where(['uid'=> $this->user->id,'shop_id' =>$param['id'],'paid_at' => 0,'is_del' => 0])->field('id,create_time')->find();
            if($info){
                $create_time = (($info->create_time + 60 * 10) - time()) * 1000;
                if($create_time < 0){
                    $info->is_del = 1;
                    $info->save();
                }
                $new_order['id']          = $info->id;
                $new_order['create_time'] = $create_time;
            }
        }
        return enjson(200,['share' => $data,'order' => $new_order]);
    }
}